package com.umeox.watch.moto.chat.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.umeox.moto.common.executor.ThreadExecutor;
import com.umeox.moto.common.utils.DateUtils;
import com.umeox.watch.moto.chat.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class Utility {
   public static boolean is24Hour;

    public static float dpToPx(Context context, float dp) {
        if (context == null) {
            return -1;
        }
        return dp * context.getResources().getDisplayMetrics().density;
    }

    public static String processName(String user) {
        return user.replace("$", "_").replace(".", "_");
    }

    /**
     * 格式化时间, 根据传入的时间与当前时间对比，返回不同的格式字符串
     * 返回格式如 传入时间距当前时间小于一天，返回当天时间 05:30AM
     * 传入时间距当前时间大一天并且小于30天，返回当天时间 一天前
     * 传入时间距当前时间大一天并且大于30天，返回当天时间 一个月前
     * 传入时间距当前时间大一天并且大于一年，返回当天时间 一年前
     *
     * @param ctx     上下文
     * @param tagTime 时间戳
     */
    public static String intervalDate(Context ctx, long tagTime) {
        if (tagTime <= 0) {
            return "";
        }

        Date date = new Date(tagTime);
        Calendar calTag = Calendar.getInstance();
        calTag.setTime(date);
        Calendar calNow = Calendar.getInstance();

        if ((calNow.getTimeInMillis() - tagTime) < TimeUnit.MINUTES.toMillis(10)) {
            return ctx.getString(R.string.message_just);
        }
        try {

            if (isSameDate(calTag, calNow)) {
                return  ctx.getString(R.string.message_other,
                        DateFormat.getTimeInstance(DateFormat.SHORT,
                                Locale.getDefault()).format(date));

            }

            int resId;
            String pattern;
            int dayNow = calNow.get(Calendar.DAY_OF_YEAR);
            int dayTag = calTag.get(Calendar.DAY_OF_YEAR);
            int i = Math.abs(dayTag - dayNow);

            if (i == 1) {
                resId = R.string.message_yesterday;
                pattern = is24Hour ? "HH:mm" : "hh:mm a";

            } else {
                resId = R.string.message_other;
                pattern = is24Hour ? "MM/dd HH:mm" : "MM/dd hh:mm a";
            }


            final SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());

            return ctx.getString(resId, format.format(date));
        } catch (Exception e) {
            return "";
        }
    }

    public static String sessionTimeFormat(Context ctx, long tagTime) {
        if (tagTime <= 0) {
            return "";
        }

        Date date = new Date(tagTime);
        Calendar calTag = Calendar.getInstance();
        calTag.setTime(date);
        Calendar calNow = Calendar.getInstance();

        if ((calNow.getTimeInMillis() - tagTime) < TimeUnit.MINUTES.toMillis(10)) {
            return ctx.getString(R.string.session_Just);
        }
        try {

            if (isSameDate(calTag, calNow)) {
                return DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date);
            }

            String pattern;
            int dayNow = calNow.get(Calendar.DAY_OF_YEAR);
            int dayTag = calTag.get(Calendar.DAY_OF_YEAR);
            int i = Math.abs(dayTag - dayNow);

            if (i == 1) {
                pattern = ctx.getString(R.string.session_yesterday);
            } else {
                final SimpleDateFormat format = new SimpleDateFormat("MM/dd", Locale.US);
                pattern = format.format(date);
            }

            return pattern;
        } catch (Exception e) {
            return "";
        }
    }

    private static boolean isSameYear(Calendar tag, Calendar current) {
        return tag.get(Calendar.YEAR) == current.get(Calendar.YEAR);
    }

    private static boolean isSameMonth(Calendar tag, Calendar current) {
        return tag.get(Calendar.MONTH) == current.get(Calendar.MONTH);
    }

    private static boolean isSameDate(Calendar tag, Calendar current) {
        return isSameYear(tag, current) && isSameMonth(tag, current) && tag.get(Calendar.DAY_OF_MONTH) == current.get(Calendar.DAY_OF_MONTH);
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private static boolean checkCameraFacing(final int facing) {
        try {
            final int cameraCount = Camera.getNumberOfCameras();
            Camera.CameraInfo info = new Camera.CameraInfo();
            for (int i = 0; i < cameraCount; i++) {
                Camera.getCameraInfo(i, info);
                if (facing == info.facing) {
                    return true;
                }
            }
        } catch (Exception ignored) {
        }
        return false;
    }

    public static boolean hasBackFacingCamera() {
        final int cameraFacingBack = 0;
        return checkCameraFacing(cameraFacingBack);
    }

    public static int getHeightInPx(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static int getWidthInPx(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(Context context, Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    /**
     * 判断是否震动模式
     */
    public static boolean isMute(Context context) {
        AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        return audio.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE;
    }


    /**
     * 图片反转
     *
     * @param bmp
     * @param flag 0为水平反转，1为垂直反转
     * @return
     */
    public static Bitmap reverseBitmap(Context context, Bitmap bmp, int flag) {
        float[] floats = null;
        // 水平反转
        // 垂直反转
        if (flag == 0) {
            floats = new float[]{-1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f};
        } else if (flag == 1) {
            floats = new float[]{1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f};
        }

        if (floats != null) {
            int width = bmp.getWidth();
            int height = bmp.getHeight();
            int screenWidth = getWidthInPx(context);
            int screenHeight = getHeightInPx(context);
            float scaleWight = ((float) screenWidth) / width;
            float scaleHeight = ((float) screenHeight) / height;
            Matrix matrix = new Matrix();
            matrix.setValues(floats);
            matrix.postScale(scaleWight, scaleHeight);
            return Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, true);
        }
        return null;
    }


    public static void saveLog(String content) {
        final String message = DateUtils.formatDateTime(System.currentTimeMillis()) + " " + content;
        ThreadExecutor.getInstance().io().execute(() -> {

            //创建一个带缓冲区的输出流
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                String logPath = sdPath + "/Dev/Chat/log/";
                File file = new File(logPath);
                FileOutputStream fos = null;
                OutputStreamWriter writer = null;
                try {
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    File logFile = new File(file, "log.txt");
                    fos = new FileOutputStream(logFile, true);
                    writer = new OutputStreamWriter(fos, "utf-8");
                    writer.write(message);
                    writer.write("\n");

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (writer != null) {
                            writer.close();
                        }

                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }
}
